package jannex.sql;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BatchExecutor {

    private final Query query;
    private final List<Iterable<Object>> arguments = new ArrayList<>();
    private boolean autoCommit = true;

    public BatchExecutor(Query query) {
        this.query = query;
    }

    public BatchExecutor add(Map<String, Object> values) {
        return add(Arrays.asList(values));
    }

    public BatchExecutor add(Object... values) {
        return add(Arrays.asList(values));
    }

    public BatchExecutor add(Iterable<Object> values) {
        arguments.add(values);
        return this;
    }

    public int[] execute() {
        try (JxPreparedStatement preparedStatement = query.build()) {
            if (!autoCommit) {
                preparedStatement.getConnection().setAutoCommit(false);
            }
            for (Iterable<Object> values : arguments) {
                int ix = 1;
                for (Object value : values) {
                    preparedStatement.setObject(ix++, value);
                }
                preparedStatement.addBatch();
            }
            int[] result = preparedStatement.executeBatch();
            if (!autoCommit) {
                preparedStatement.getConnection().commit();
            }
            return result;
        }
    }


    // TODO should fix Query version first
    // public BatchExecutor addFrom(Object object) {

    public BatchExecutor autoCommit(boolean autoCommit) {
        this.autoCommit = autoCommit;
        return this;
    }

}
